package com.saascloud.auth.core;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

//@Component
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.error("无权访问.authException403", accessDeniedException);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",403);
        map.put("result","无权访问");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html; charset=utf-8");
        //按照系统自定义结构返回授权失败
        response.getWriter().write(JSONUtil.toJsonStr(map));
    }
}
